// 工作流表单设计器
$.fn.workflowFormDesign = function(options){
    // 属性
    var options = $.extend({
        // 表单项类型
        "itemType": {
            "workflowItemTypeFromUser": "workflow-from-user",           // 发起人名称
            "workflowItemTypeCreatetime": "workflow-createtime",        // 发起时间
            "workflowItemTypeText": "workflow-text",                    // 文本框
            "workflowItemTypeTime": "workflow-time",                    // 时间选择
            "workflowItemTypeSelect": "workflow-select",                // 下拉选择
            "workflowItemTypeFile": "workflow-file",                    // 文件上传
            "workflowItemTypeContent": "workflow-content",              // 富文本编辑器
        },
        // timeformat
        "timeFormat": {
            "YYYY-MM-DD HH:mm:ss": "2019-05-31 17:00:00",
            "YYYY-MM-DD HH:mm": "2019-05-31 17:00",
            "YYYY-MM-DD": "2019-05-31",
            "HH:mm:ss": "17:00:00",
            "HH:mm": "17:00",
        },
        // 可拖动元素容器
        "draggableDom": null,
        // 接收元素容器
        "droppableDom": null,
        // 属性弹窗对象
        "attrModal": null,
        // 初始化表单对象
        "formData": null,
        // 回调函数
        callback: function(){}
    }, options);

    // 可拖动元素DOM对象
    var draggableDom = options.draggableDom;
    // 接收拖动元素
    var droppableDom = options.droppableDom;

    // 方法
    var workflowFormFunction = {
        // 初始化表单设计器
        "design_init": function() {

            // 添加表单项
            draggableDom.append('<div class="draggable-item external-event label-grey" data-type="'+ options.itemType.workflowItemTypeFromUser +'"><i class="ace-icon fa fa-arrows"></i> 发起人姓名（内容只读）</div>');
            draggableDom.append('<div class="draggable-item external-event label-grey" data-type="'+ options.itemType.workflowItemTypeCreatetime +'"><i class="ace-icon fa fa-arrows"></i> 发起时间（内容只读）</div>');
            draggableDom.append('<div class="draggable-item external-event label-success" data-type="'+ options.itemType.workflowItemTypeText +'"><i class="ace-icon fa fa-arrows"></i> 文本框</div>');
            draggableDom.append('<div class="draggable-item external-event label-danger" data-type="'+ options.itemType.workflowItemTypeTime +'"><i class="ace-icon fa fa-arrows"></i> 日期时间选择</div>');
            draggableDom.append('<div class="draggable-item external-event label-danger" data-type="'+ options.itemType.workflowItemTypeSelect +'"><i class="ace-icon fa fa-arrows"></i> 下拉选择</div>');
            draggableDom.append('<div class="draggable-item external-event label-purple" data-type="'+ options.itemType.workflowItemTypeFile +'"><i class="ace-icon fa fa-arrows"></i> 文件上传</div>');
            draggableDom.append('<div class="draggable-item external-event label-info" data-type="'+ options.itemType.workflowItemTypeContent +'"><i class="ace-icon fa fa-arrows"></i> 富文本内容</div>');
            draggableDom.append('<a class="btn btn-info mt20" id="save-workflow-design"><i class="ace-icon fa fa-check"></i> 保存表单内容</a>');

            // 初始化可拖动元素
            draggableDom.find(".draggable-item").draggable({
                zIndex: 999,
                revert: true,
                revertDuration: 0
            });

            // 接收拖动元素
            droppableDom.droppable({
                // 拖入div事件
                over: function(event, ui) {
                    var target = $(event.target);
                    // 添加占位符
                    target.append('<div class="workflow-item-placeholder">松开鼠标，创建元素</div>');
                },
                // 拖出div事件
                out: function(event, ui) {
                    var target = $(event.target);
                    // 移除占位符
                    target.find(".workflow-item-placeholder").remove();
                },
                // 放入div事件
                drop: function(event, ui) {
                    var target = $(event.target);
                    var itemUi = $(ui.draggable.context);
                    // 生成表单项
                    workflowFormFunction.create_design_item({
                        "itemPlaceholder": target.find(".workflow-item-placeholder"),
                        "type": itemUi.data("type")
                    });
                    // 移除占位符
                    target.find(".workflow-item-placeholder").remove();
                }
            });

            // 初始化属性弹窗对象
            options.attrModal = $('<div class="modal fade">\
                <div class="modal-dialog">\
                    <div class="modal-content">\
                        <div class="modal-header no-padding">\
                            <div class="table-header">\
                                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">\
                                    <span class="white">&times;</span>\
                                </button> 表单项属性管理器\
                            </div>\
                        </div>\
                        <div class="modal-body no-padding">\
                            <div class="row">\
                                <div class="col-xs-12">\
                                    <form class="form-horizontal mt10" id="modal-body"></form>\
                                </div>\
                            </div>\
                        </div>\
                        <div class="modal-footer no-margin-top" >\
                            <a href="javascript:;" class="btn btn-sm btn-primary" id="save-modal">\
                                <i class="ace-icon fa fa-check"></i> 保存\
                            </a>\
                        </div>\
                    </div>\
                </div>\
            </div>');

            // 编辑表单元素
            $("body").on("click", ".workflow-design-item-setting", function(){
                var itemJson = {
                    "designItem": $(this).closest(".workflow-design-item"),
                    "itemLabel": $(this).closest(".workflow-design-item").data("label"),
                    "itemType": $(this).closest(".workflow-design-item").data("type"),
                    "timeFormat": $(this).closest(".workflow-design-item").data("format"),
                    "selectOptions": $(this).closest(".workflow-design-item").data("options"),
                };

                // 根据不同的类型，弹出不同的设置窗口
                switch(itemJson.itemType) {
                    // 发起人信息
                    case options.itemType.workflowItemTypeFromUser:
                    // 发起时间
                    case options.itemType.workflowItemTypeCreatetime:
                    // 文本框
                    case options.itemType.workflowItemTypeText:
                    // 文件上传
                    case options.itemType.workflowItemTypeFile:
                    // 富文本编辑器
                    case options.itemType.workflowItemTypeContent:
                        workflowFormFunction.design_item_modal.label_modal(itemJson);
                        break;
                    // 时间选择
                    case options.itemType.workflowItemTypeTime:
                        workflowFormFunction.design_item_modal.time_modal(itemJson);
                        break;
                    // 下拉选择
                    case options.itemType.workflowItemTypeSelect:
                        workflowFormFunction.design_item_modal.select_modal(itemJson);
                        break;
                }
            })

            // 移除表单元素
            $("body").on("click", ".workflow-design-item-remove", function(){
                var item = $(this).closest(".workflow-design-item");
                layer.confirm('表单项删除后无法恢复，请谨慎操作', function(index){
                    layer.close(index);
                    item.remove();
                });
            })

            // 提交表单
            draggableDom.on("click", "#save-workflow-design", function(e) {
                var itemData = {};
                $(".workflow-design-item").each(function(){
                    var id = $(this).attr("id");
                    // 标签和格式
                    itemData[id] = {
                        "type": $(this).data('type'),
                        "label": $(this).data("label")
                    }
                    // 时间格式
                    if(typeof $(this).data("format") != 'undefined') itemData[id].timeFormat = $(this).data("format");
                    // 下拉选项
                    if(typeof $(this).data("options") != 'undefined') itemData[id].selectOptions = $(this).data("options");
                })
                // 执行回调
                options.callback(itemData);
            })

            // 如果有初始化对象
            if(options.formData) {
                for(var itemId in options.formData) {
                    var formItem = options.formData[itemId];
                    // 初始化对象
                    formItem.id = itemId;
                    formItem.itemPlaceholder = droppableDom.find(".workflow-design-form-bottom");
                    workflowFormFunction.create_design_item(formItem);
                }
            }
        },
        // 创建表单元素
        "create_design_item": function(dataJson){
            // 表单项占位符
            var itemPlaceholder = dataJson.itemPlaceholder;
            // 表单项类型
            var itemType = dataJson.type;
            // 表单项ID
            var itemId = typeof dataJson.id != 'undefined' ? dataJson.id : "id_" + parseInt(Math.random() * 10000000);
            // 表单项子元素ID
            var itemChildId = "id_" + parseInt(Math.random() * 10000);
            // 表单项标签
            var itemLabel = typeof dataJson.label != 'undefined' ? dataJson.label : '';
            // 表单项时间格式
            var itemTimeFormat = typeof dataJson.timeFormat != 'undefined' ? dataJson.timeFormat : '';
            // 表单项下拉菜单选项
            var itemSelectOptions = typeof dataJson.selectOptions != 'undefined' ? dataJson.selectOptions : '';

            // 生成不同的表单内容
            switch(itemType) {
                // 发起人
                case options.itemType.workflowItemTypeFromUser:
                    var label = itemLabel ? itemLabel : '发起人姓名';

                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ label +'" data-type="'+ itemType +'">\
                            <label class="col-sm-3 control-label no-padding-right">'+ label +'：</label>\
                            <div class="col-sm-9">\
                                <input class="col-sm-8" type="text" value="刘远" readonly="">\
                                <a href="javascript:;" class="workflow-design-item-setting mr10"><i class="fa fa-edit"></i> 属性设置</a>\
                                <a href="javascript:;" class="workflow-design-item-remove text-danger"><i class="fa fa-times"></i> 移除</a>\
                            </div>\
                        </div>');
                    break;
                // 发起时间
                case options.itemType.workflowItemTypeCreatetime:
                    var label = itemLabel ? itemLabel : '发起时间';

                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ label +'" data-type="'+ itemType +'">\
                            <label class="col-sm-3 control-label no-padding-right">'+ label +'：</label>\
                            <div class="col-sm-9">\
                                <input class="col-sm-8" type="text" value="2019-05-31 17:30" readonly="">\
                                <a href="javascript:;" class="workflow-design-item-setting mr10"><i class="fa fa-edit"></i> 属性设置</a>\
                                <a href="javascript:;" class="workflow-design-item-remove text-danger"><i class="fa fa-times"></i> 移除</a>\
                            </div>\
                        </div>');
                    break;
                // 文本框
                case options.itemType.workflowItemTypeText:
                    var label = itemLabel ? itemLabel : '工作流标题';

                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ label +'" data-type="'+ itemType +'">\
                            <label class="col-sm-3 control-label no-padding-right">'+ label +'：</label>\
                            <div class="col-sm-9">\
                                <input class="col-sm-8" type="text" value="">\
                                <a href="javascript:;" class="workflow-design-item-setting mr10"><i class="fa fa-edit"></i> 属性设置</a>\
                                <a href="javascript:;" class="workflow-design-item-remove text-danger"><i class="fa fa-times"></i> 移除</a>\
                            </div>\
                        </div>');
                    break;
                // 日期时间选择
                case options.itemType.workflowItemTypeTime:
                    var label = itemLabel ? itemLabel : '请假开始时间';
                    // 时间格式
                    var defaultFormat = itemTimeFormat ? itemTimeFormat : "YYYY-MM-DD HH:mm:ss";
                    var formatValue = options.timeFormat[defaultFormat];

                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ label +'" data-type="'+ itemType +'" data-format="'+ defaultFormat +'">\
                            <label class="col-sm-3 control-label no-padding-right">'+ label +'：</label>\
                            <div class="col-sm-9">\
                                <input class="col-sm-8" type="text" value="'+ formatValue +'">\
                                <a href="javascript:;" class="workflow-design-item-setting mr10"><i class="fa fa-edit"></i> 属性设置</a>\
                                <a href="javascript:;" class="workflow-design-item-remove text-danger"><i class="fa fa-times"></i> 移除</a>\
                            </div>\
                        </div>');
                    break;
                // 下拉选择
                case options.itemType.workflowItemTypeSelect:
                    var label = itemLabel ? itemLabel : '类型选择';
                    // 下拉选项
                    var optionHtml = '<option>请选择对应的类型</option>';
                    if(itemSelectOptions != '') {
                        var optionsArray = itemSelectOptions.split(", ");
                        optionHtml = "";
                        for(var i in optionsArray) optionHtml += '<option value="'+ optionsArray[i] +'">'+ optionsArray[i] +'</option>';
                    }


                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ label +'" data-type="'+ itemType +'" data-options="'+ itemSelectOptions +'">\
                        <label class="col-sm-3 control-label no-padding-right">'+ label +'：</label>\
                        <div class="col-sm-9">\
                            <select class="col-sm-8 pd0">'+ optionHtml +'</select>\
                            <a href="javascript:;" class="workflow-design-item-setting mr10"><i class="fa fa-edit"></i> 属性设置</a>\
                            <a href="javascript:;" class="workflow-design-item-remove text-danger"><i class="fa fa-times"></i> 移除</a>\
                        </div>\
                    </div>');
                    break;
                // 文件上传
                case options.itemType.workflowItemTypeFile:
                    var label = itemLabel ? itemLabel : '文件上传';
                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ label +'" data-type="'+ itemType +'">\
                        <label class="col-sm-3 control-label no-padding-right">'+ label +'：</label>\
                        <div class="col-sm-9" style="padding-top: 9px;">\
                            <div class="col-sm-8 no-border" style="line-height:35px">\
                                <a href="javascript:;" class="" id="upload-file"><i class="fa fa-file"></i> 上传附件</a>\
                            </div>\
                            <span>\
                                <a href="javascript:;" class="workflow-design-item-setting mr10"><i class="fa fa-edit"></i> 属性设置</a>\
                                <a href="javascript:;" class="workflow-design-item-remove text-danger"><i class="fa fa-times"></i> 移除</a>\
                            </span>\
                        </div>\
                    </div>');
                    break;
                // 富文本编辑器
                case options.itemType.workflowItemTypeContent:
                    var label = itemLabel ? itemLabel : '内容说明';
                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ label +'" data-type="'+ itemType +'" data-options="">\
                        <label class="col-sm-3 control-label no-padding-right">'+ label +'：</label>\
                        <div class="col-sm-9">\
                            <div class="col-sm-8 no-border" style="padding-top: 10px;">\
                                <div id="'+ itemChildId +'" style="width:100%;height:120px"></div>\
                            </div>\
                            <a href="javascript:;" class="workflow-design-item-setting mr10"><i class="fa fa-edit"></i> 属性设置</a>\
                            <a href="javascript:;" class="workflow-design-item-remove text-danger"><i class="fa fa-times"></i> 移除</a>\
                        </div>\
                    </div>');
                    // 初始化百度编辑器
                    var ue = UE.getEditor(itemChildId);
                    break;
            }
        },
        // 表单属性弹窗
        "design_item_modal": {
            // 标签弹窗
            "label_modal" : function(dataJson){
                var itemLabel = dataJson.itemLabel;
                // 替换弹窗内容
                workflowFormFunction.design_item_modal.init_modal('<div class="form-group">\
                    <label class="col-sm-3 control-label no-padding-right">字段名称：</label>\
                    <div class="col-sm-6">\
                        <input class="form-control" type="text" name="label" placeholder="请填写字段名称" value="'+ itemLabel +'"/>\
                    </div>\
                </div>', function(currentAttrModal, formData){
                    // 重写表单项
                    dataJson.designItem.data('label', formData.label);
                    dataJson.designItem.find(".control-label").html(formData.label + "：");

                    currentAttrModal.modal("hide");
                });
            },
            // 时间弹窗
            "time_modal" : function(dataJson){
                var itemLabel = dataJson.itemLabel;
                var timeFormat = dataJson.timeFormat;

                // 替换弹窗内容
                workflowFormFunction.design_item_modal.init_modal('<div class="form-group">\
                    <label class="col-sm-3 control-label no-padding-right">字段名称：</label>\
                    <div class="col-sm-6">\
                        <input class="form-control" type="text" name="label" placeholder="请填写字段名称" value="'+ itemLabel +'"/>\
                    </div>\
                </div>\
                <div class="form-group">\
                    <label class="col-sm-3 control-label no-padding-right">时间格式：</label>\
                    <div class="col-sm-6">\
                        <select class="form-control" name="format">\
                            <option value="YYYY-MM-DD HH:mm:ss">完整时间（例：2019-05-31 17:00:00）</option>\
                            <option value="YYYY-MM-DD HH:mm">年月日 时分（例：2019-05-31 17:00）</option>\
                            <option value="YYYY-MM-DD">年月日（例：2019-05-31）</option>\
                            <option value="HH:mm:ss">时分秒（例：17:00:00）</option>\
                            <option value="HH:mm">时分（例：17:00）</option>\
                        </select>\
                    </div>\
                </div>', function(currentAttrModal){
                    // 弹窗初始化方法
                    currentAttrModal.find("[name=format]").val(timeFormat);
                }, function(currentAttrModal, formData){
                    // 弹窗回调方法
                    dataJson.designItem.data('label', formData.label);
                    dataJson.designItem.data('format', formData.format);
                    dataJson.designItem.find(".control-label").html(formData.label + "：");
                    dataJson.designItem.find("input.col-sm-8").val(options.timeFormat[formData.format]);
                    currentAttrModal.modal("hide");
                });

                
            },
            // 下拉选择弹窗
            "select_modal" : function(dataJson){
                var itemLabel = dataJson.itemLabel;
                var itemOptions = dataJson.selectOptions;

                // 替换弹窗内容
                workflowFormFunction.design_item_modal.init_modal('<div class="form-group">\
                    <label class="col-sm-3 control-label no-padding-right">字段名称：</label>\
                    <div class="col-sm-6">\
                        <input class="form-control" type="text" name="label" placeholder="请填写字段名称" value="'+ itemLabel +'"/>\
                    </div>\
                </div><div class="form-group">\
                    <label class="col-sm-3 control-label no-padding-right">下拉框内容：</label>\
                    <div class="col-sm-6">\
                        <input class="form-control" type="text" name="options" placeholder="请填写字段名称" value="'+ itemOptions +'"/>\
                    </div>\
                </div>', function(currentModal){
                    // 弹窗初始化方法
                    currentModal.find("[name=options]").tag({
                        placeholder: currentModal.find("[name=options]").attr('placeholder'),
                    })
                }, function(currentAttrModal, formData){
                    // 弹窗回调方法
                    dataJson.designItem.data('label', formData.label);
                    dataJson.designItem.data('options', formData.options);
                    dataJson.designItem.find(".control-label").html(formData.label + "：");
                    // 获取下拉数组
                    var optionsArray = formData.options.split(",");
                    var optionsHtml = "";
                    for(var i in optionsArray) optionsHtml += '<option value="'+ optionsArray[i] +'">'+ optionsArray[i] +'</option>';
                    dataJson.designItem.find("select").html(optionsHtml);

                    currentAttrModal.modal("hide");
                });
            },
            // 初始化弹窗
            // 如果只传2个参数，那么第二个参数就是关闭弹窗回调
            // 如果有3个参数，那么第二个参数是打开弹窗回调，第三个参数是关闭弹窗回调
            "init_modal": function(modalContent, callback, callback2){
                var currentModal = options.attrModal;
                currentModal.find("#modal-body").html(modalContent);
                currentModal.modal();

                // 如果存在第三个参数
                if(typeof callback2 != 'undefined') callback(currentModal);

                // 点击事件
                currentModal.find("#save-modal").unbind("click").bind("click", function(){
                    var formData = {};
                    currentModal.find("[name]").each(function(){
                        var itemName = $(this).attr("name");
                        formData[itemName] = $(this).val();
                    })
                    // 触发回调
                    if(typeof callback2 == 'undefined') callback(currentModal, formData);
                    else callback2(currentModal, formData);
                })
            }
        }
    }

    // 初始化方法
    workflowFormFunction.design_init();     
}

// 工作流流程设计器
$.fn.workflowProcessDesign = function(options){
    // 属性
    var options = $.extend({
        // 流程节点类型
        "nodeType": {
            "workflowNodeTypeStart": "workflow-process-node-start",           // 开始节点
            "workflowNodeTypeApproval": "workflow-process-node-approval",     // 审批节点
            "workflowNodeTypeEnd": "workflow-process-node-end",               // 结束节点
        },
        // 可拖动元素容器
        "draggableDom": null,
        // 接收元素容器
        "droppableDom": null,
        // 节点数据
        "nodeJson": {},
        // 检查是否长按拖动事件
        "isLongPressTimeCheck": null,
        "isLongPress": false,
        // 是否只读模式
        "isReadOnly": false,
        // 回调函数
        callback: function(){}
    }, options);

    // 可拖动元素DOM对象
    var draggableDom = options.draggableDom;
    // 接收拖动元素
    var droppableDom = options.droppableDom;

    // 方法
    var workflowProcessFunction = {
        // 初始化流程设计器
        "design_init": function() {
            // 添加节点
            draggableDom.append('<div class="draggable-node external-event label-success" data-type="'+ options.nodeType.workflowNodeTypeStart +'"><i class="ace-icon fa fa-arrows"></i> 开始节点</div>');
            draggableDom.append('<div class="draggable-node external-event label-info" data-type="'+ options.nodeType.workflowNodeTypeApproval +'"><i class="ace-icon fa fa-arrows"></i> 审批节点</div>');
            draggableDom.append('<div class="draggable-node external-event label-grey" data-type="'+ options.nodeType.workflowNodeTypeEnd +'"><i class="ace-icon fa fa-arrows"></i> 结束节点</div>');
            draggableDom.append('<a class="btn btn-info mt20" id="save-workflow-design"><i class="ace-icon fa fa-check"></i> 保存工作流流程</a>');

            // 初始化可拖动元素
            draggableDom.find(".draggable-node").draggable({
                zIndex: 999,
                revert: true,
                revertDuration: 0
            });

            // 接收拖动元素
            droppableDom.droppable({
                // 放入div事件
                drop: function(event, ui) {
                    var target = $(event.target);
                    var nodeItem = $(ui.draggable.context);
                    // 获取元素在设计器上的坐标
                    var positionLeft = target.width() + ui.position.left;
                    var positionTop = ui.position.top;
                    // 生成节点
                    var nodeData = {
                        "offsetLeft": positionLeft,
                        "offsetTop": positionTop,
                        "type": nodeItem.data("type")
                    }
                    workflowProcessFunction.create_process_design_node(nodeData);
                }
            }).height($(document).height() - 263);

            // 提交表单
            draggableDom.on("click", "#save-workflow-design", function(e) {
                // 获取所有节点位置
                for(var i in options.nodeJson) {
                    // 获取节点对象
                    var nodeDom = droppableDom.find("#" + i);
                    options.nodeJson[i].offsetLeft = nodeDom[0].offsetLeft;
                    options.nodeJson[i].offsetTop = nodeDom[0].offsetTop;
                }

                var connections = jsPlumb.getAllConnections();
                for(var i in connections) {
                    // 起始节点
                    var startPoint = connections[i]['endpoints'][0];
                    var startId = startPoint.elementId;
                    // 目标节点
                    var endPoint = connections[i]['endpoints'][1];
                    // 连线
                    var connId = connections[i]['id'];
                    // 设置连线连接位置
                    options.nodeJson[startId]['links'][connId]['startAnchor'] = startPoint.anchor.type;
                    options.nodeJson[startId]['links'][connId]['endAnchor'] = endPoint.anchor.type;
                }

                // 执行回调
                options.callback(options.nodeJson);
            })

            // 如果有初始化数据
            for(var i in options.nodeJson) {
                var nodeData = options.nodeJson[i];
                // 初始化一个节点ID
                nodeData.id = i;
                workflowProcessFunction.create_process_design_node(nodeData);
            }
            // 连接节点
            for(var i in options.nodeJson) {
                var nodeLinks = options.nodeJson[i]['links'];
                if(typeof nodeLinks != 'undefined') {
                    for(var j in nodeLinks) {
                        var link = nodeLinks[j];
                        // 将节点连线
                        var conn = jsPlumb.connect({
                            uuids: [i + "_" + link.startAnchor, link.target + "_" + link.endAnchor],
                        })
                        conn.setType(link.result);
                        conn.id = j;
                    }
                }
            }
        },
        // 创建表单元素
        "create_process_design_node": function(dataJson){
            // 节点位置
            var nodeLeft = dataJson.offsetLeft;
            var nodeTop = dataJson.offsetTop;
            // 表单项类型
            var nodeType = dataJson.type;
            // 表单项ID
            var nodeId = typeof dataJson.id != 'undefined' ? dataJson.id : "id_" + parseInt(Math.random() * 10000000);

            // 生成不同的表单内容
            switch(nodeType) {
                // 流程开始节点
                case options.nodeType.workflowNodeTypeStart:
                    // 检查是否已经存在开始节点
                    if(droppableDom.find("." + nodeType).length) {
                        layer.msg('开始节点已存在，请勿重复添加');
                        return;
                    }
                    // 如果是开始节点，id就叫start
                    nodeId = 'start';
                    // 添加节点
                    droppableDom.append('<a id="'+ nodeId +'" href="javascript:;" class="node-item '+ nodeType +'" style="left:'+ nodeLeft +'px;top:'+ nodeTop +'px"><i class="fa fa-play"></i>&nbsp;&nbsp;流程开始</a>');
                    // 初始化节点
                    workflowProcessFunction.init_process_node(nodeId, dataJson);
                    break;
                // 流程审批节点
                case options.nodeType.workflowNodeTypeApproval:
                    // 添加节点
                    droppableDom.append('<a id="'+ nodeId +'" href="javascript:;" class="node-item '+ nodeType +'" style="left:'+ nodeLeft +'px;top:'+ nodeTop +'px"><i class="fa fa-user"></i>&nbsp;&nbsp;<span class="name">选择审批人</span><p class="remark"></p></a>');
                    // 初始化节点
                    workflowProcessFunction.init_process_node(nodeId, dataJson);
                    break;
                // 流程结束节点
                case options.nodeType.workflowNodeTypeEnd:
                    // 检查是否已经存在结束节点
                    if(droppableDom.find("." + nodeType).length) {
                        layer.msg('结束节点已存在，请勿重复添加');
                        return;
                    }
                    // 如果是结束节点，id就叫end
                    nodeId = 'end';
                    // 添加节点
                    droppableDom.append('<a id="'+ nodeId +'" href="javascript:;" class="node-item '+ nodeType +'" style="left:'+ nodeLeft +'px;top:'+ nodeTop +'px"><i class="fa fa-stop"></i>&nbsp;&nbsp;流程结束</a>');
                    // 初始化节点
                    workflowProcessFunction.init_process_node(nodeId, dataJson);
                    break;
            }
        },
        // 初始化流程节点
        "init_process_node": function(nodeId, dataJson){
            var nodeType = dataJson.type;
            var anchors = [];
            // 其他配置信息
            switch(nodeType) {
                // 流程开始节点
                case options.nodeType.workflowNodeTypeStart:
                    anchors = typeof dataJson.anchors == 'undefined' ? ['Right'] : dataJson.anchors;
                    break;
                // 流程审批节点
                case options.nodeType.workflowNodeTypeApproval:
                case options.nodeType.workflowNodeTypeEnd:
                    anchors = typeof dataJson.anchors == 'undefined' ? ['Top','Right', 'Bottom', 'Left'] : dataJson.anchors;
                    break;
            }

            // 配置参数
            var nodeConfig = {
                // 这两个参数是支持拖动并创建连接
                isSource: nodeType == options.nodeType.workflowNodeTypeEnd ? false : true,
                isTarget: true,
                paintStyle: { fill: '#303030', radius: 5, lineWidth: 2},
                // 最大连接线
                maxConnections: nodeType == options.nodeType.workflowNodeTypeEnd ? -1 : 1,
                // 连接线设置
                connector: ['Flowchart'],
                connectorStyle: { outlineStroke: '#D15B47', strokeWidth: 3},
                connectorOverlays: [
                    ['Arrow', { width: 20, length: 20, location: 1, paintStyle: {"fill": '#D15B47'}}]
                ]
            }

            // 创建节点
            for(var i in anchors) {
                var point = jsPlumb.addEndpoint(nodeId, {
                    anchors: anchors[i],
                    uuid: nodeId + "_" + anchors[i]
                }, nodeConfig);
            }

            // 设置节点允许拖动
            jsPlumb.draggable(nodeId, {"containment": 'parent'});

            // 检查是否有该配置项。如果没有，就是创建新节点，有的话就需要初始化数据
            if(typeof options.nodeJson[nodeId] == 'undefined') {
                // 写入配置信息
                options.nodeJson[nodeId] = {
                    "type": nodeType,
                    "anchors": anchors,
                    "approvalUser": {},
                    "approvalRemark": "",
                    "links": {}
                };

                // 如果是审批节点，需要一个弹窗
                if(nodeType == options.nodeType.workflowNodeTypeApproval) workflowProcessFunction.show_node_modal(nodeId);
            } else {
                // 初始化节点数据
                workflowProcessFunction.init_approval_node(nodeId);

            }

            // 节点点击事件
            if(nodeType == options.nodeType.workflowNodeTypeApproval) {
                // 检查如果是拖动，则不触发点击事件
                droppableDom.find("#" + nodeId).unbind("mousedown").bind("mousedown", function(){
                    options.isLongPress = false;
                    options.isLongPressTimeCheck = setTimeout(function(){
                        options.isLongPress = true;
                    }, 300);
                })
                droppableDom.find("#" + nodeId).unbind("mouseup").bind("mouseup", function(){
                    clearTimeout(options.isLongPressTimeCheck);
                })
                droppableDom.find("#" + nodeId).unbind("click").bind("click", function(){
                    if(options.isLongPress) return;
                    workflowProcessFunction.show_node_modal(nodeId);
                })
            }

        },
        // 显示连接管理器
        "show_links_modal": function(sourceId, connObject, connId){
            // 连线结果
            var linkOptions = "";
            if(sourceId == 'start') {
                linkOptions = '<option value="start">发起</option>';
            } else {
                linkOptions = '<option value="pass">同意</option><option value="refuse">拒绝</option>';
            }

            // 初始化属性弹窗对象
            var linksModal = $('<div class="modal fade">\
                <div class="modal-dialog">\
                    <div class="modal-content">\
                        <div class="modal-header no-padding">\
                            <div class="table-header">\
                                审核结果管理器\
                            </div>\
                        </div>\
                        <div class="modal-body no-padding">\
                            <div class="row">\
                                <div class="col-xs-12">\
                                    <form class="form-horizontal mt10">\
                                        <div class="form-group">\
                                            <label class="col-sm-3 control-label no-padding-right">审批结果选择：</label>\
                                            <div class="col-sm-6">\
                                                <select class="form-control">'+ linkOptions +'</select>\
                                            </div>\
                                        </div>\
                                    </form>\
                                </div>\
                            </div>\
                        </div>\
                        <div class="modal-footer no-margin-top" >\
                            <a href="javascript:;" class="btn btn-sm btn-primary">\
                                <i class="ace-icon fa fa-check"></i> 保存\
                            </a>\
                        </div>\
                    </div>\
                </div>\
            </div>');
            linksModal.modal({
                backdrop: 'static', 
                keyboard: false
            });

            // 点击关闭事件
            linksModal.find(".btn-primary").unbind("click").bind("click", function(){
                var approvalResult = linksModal.find("select").val();
                // 检查是否存在2条同类型的线
                var links = options.nodeJson[sourceId]['links'];
                for(var i in links) {
                    if(i != connId && links[i].result == approvalResult) {
                        layer.msg('同一个节点不能有两个相同的审批结果');
                        return;
                    }
                }

                // 写入节点数据
                links[connId]['result'] = approvalResult;
                // 重新连接两个点
                connObject.setType(approvalResult);

                linksModal.modal("hide");
            })
        },
        // 显示节点管理器
        "show_node_modal": function(nodeId){
            // 初始化属性弹窗对象
            var nodeModal = $('<div class="modal fade">\
                <div class="modal-dialog">\
                    <div class="modal-content">\
                        <div class="modal-header no-padding">\
                            <div class="table-header">\
                                审核人管理器\
                            </div>\
                        </div>\
                        <div class="modal-body no-padding">\
                            <div class="row">\
                                <div class="col-xs-12">\
                                    <form class="form-horizontal mt10">\
                                        <div class="form-group">\
                                            <label class="col-sm-3 control-label no-padding-right">审批人选择：</label>\
                                            <div class="col-sm-6">\
                                                <span class="block input-icon input-icon-right pd0">\
                                                    <input class="width-100" type="text" placeholder="请选择审批人" id="select-approval-user" value="" />\
                                                    <input type="hidden" id="select-approval-user-value" />\
                                                    <i class="ace-icon fa fa-user"></i>\
                                                </span>\
                                            </div>\
                                        </div>\
                                        <div class="form-group">\
                                            <label class="col-sm-3 control-label no-padding-right">流程备注：</label>\
                                            <div class="col-sm-6">\
                                                <input type="text" placeholder="请填写流程备注" class="form-control" id="approval-remark" value=""/>\
                                            </div>\
                                        </div>\
                                    </form>\
                                </div>\
                            </div>\
                        </div>\
                        <div class="modal-footer no-margin-top" >\
                            <a href="javascript:;" class="btn btn-sm btn-danger">\
                                <i class="ace-icon fa fa-times"></i> 删除节点\
                            </a>\
                            <a href="javascript:;" class="btn btn-sm btn-primary">\
                                <i class="ace-icon fa fa-check"></i> 保存审批人\
                            </a>\
                        </div>\
                    </div>\
                </div>\
            </div>');

            // 检查该节点是否有数据
            var nodeData = options.nodeJson[nodeId];
            if(typeof nodeData != 'undefined') {
                var userData = nodeData['approvalUser'];

                // 初始化选择框的值
                var userName = [];
                var userId = [];
                for(var i in userData) {
                    userName.push(userData[i].name);
                    userId.push(i);
                }
                // 给选人框赋值
                if(userId.length){
                    nodeModal.find("#select-approval-user").val(userName.join("，")).data("user", JSON.stringify(userData));
                    nodeModal.find("#select-approval-user-value").val(userId.join(","));
                }
                // 给备注框赋值
                nodeModal.find("#approval-remark").val(nodeData['approvalRemark']);
            }

            nodeModal.modal({
                backdrop: 'static', 
                keyboard: false
            });

            // 初始化选人控件
            nodeModal.find("#select-approval-user").selectTeacher({
                "multiSelect": true,
                "emptyMsg": "请选择审批人",
                "resultDom": nodeModal.find("#select-approval-user-value"),
                "callback": function(result) {
                    var userName = [];
                    var userId = [];
                    for(var i in result) {
                        userName.push(result[i].name);
                        userId.push(i);
                    }
                    // 显示选择结果
                    nodeModal.find("#select-approval-user").val(userName.join("，")).data("user", JSON.stringify(result)).data("name", userName.join("，"));
                    nodeModal.find("#select-approval-user-value").val(userId.join(","));
                }
            });

            // 删除节点
            nodeModal.find(".btn-danger").unbind("click").bind("click", function(){
                layer.confirm('节点删除后无法恢复，请谨慎操作', function(index){
                    layer.close(index);
                    // 删除节点数据
                    delete options.nodeJson[nodeId];
                    // 删除节点
                    jsPlumb.remove(nodeId);
                    nodeModal.modal("hide");
                });
            })

            // 点击关闭事件
            nodeModal.find(".btn-primary").unbind("click").bind("click", function(){
                var approvalData = nodeModal.find("#select-approval-user").data("user");
                if(!approvalData) {
                    layer.msg('请选择审批人');
                    return;
                }
                var userData = JSON.parse(approvalData);

                // 写入流程数据
                options.nodeJson[nodeId]['approvalUser'] = userData;
                options.nodeJson[nodeId]['approvalRemark'] = nodeModal.find("#approval-remark").val();
                // 重新初始化审批节点
                workflowProcessFunction.init_approval_node(nodeId);
                // 隐藏弹窗
                nodeModal.modal("hide");
            })
        },
        // 初始化审批节点
        "init_approval_node": function(nodeId){
            var nodeData = options.nodeJson[nodeId];
            // 获取姓名
            var nameArray = [];
            for(var i in nodeData.approvalUser) nameArray.push(nodeData.approvalUser[i].name);
            // 写入审批人姓名
            droppableDom.find("#" + nodeId).find(".name").text(nameArray.join("，"));
            // 获取备注内容
            var remarkHtml = nodeData.approvalRemark ? '<i class="fa fa-bookmark"></i>&nbsp;&nbsp;'+ nodeData.approvalRemark : '';
            droppableDom.find("#" + nodeId).find(".remark").html(remarkHtml)
            // 重绘元素
            jsPlumb.revalidate(nodeId)
        }
    }

    // jsPlumb 初始化
    jsPlumb.ready(function () {
        //  连线建立前事件
        jsPlumb.bind("beforeDrop", function(info) {
            var sourceId = info.sourceId;
            var targetId = info.targetId;
            var connObject = info.connection;
            var connId = info.connection.id;
            // 阻止连接自身
            if(sourceId == targetId) return;
            // 连接数限制
            var nodeLinks = options.nodeJson[sourceId]['links'];
            var nodeLinksNumber = 0;
            for(var i in nodeLinks) nodeLinksNumber ++;
            if(nodeLinksNumber >= 2) {
                layer.msg('节点自身只能外联两个节点');
                return;
            }
            workflowProcessFunction.show_links_modal(sourceId, connObject, connId);

            // 写入到节点数据
            options.nodeJson[sourceId]['links'][connId] = {
                "target": targetId
            }
            return true;
        });

        // 连接移除事件
        jsPlumb.bind("connectionDetached", function(info) {
            var sourceId = info.sourceId;
            var connId = info.connection.id;
            // 删除节点数据
            delete options.nodeJson[sourceId]['links'][connId];
        })

        // 初始化设计器
        workflowProcessFunction.design_init();
    })

    // 连线选择审批结果
    // 开始
    jsPlumb.registerConnectionType('start', {
        overlays:[
            [ "Label", {label:"<a href='javascript:;' class='connect-label connect-label-start'><i class='fa fa-check'></i> 发起</a>"}]
        ], 
    });
    // 同意
    jsPlumb.registerConnectionType('pass', {
        overlays:[
            [ "Label", {label:"<a href='javascript:;' class='connect-label connect-label-pass'><i class='fa fa-check'></i> 同意</a>"}]
        ], 
    });
    // 拒绝
    jsPlumb.registerConnectionType('refuse', {
        overlays:[
            [ "Label", {label:"<a href='javascript:;' class='connect-label connect-label-refuse'><i class='fa fa-times'></i> 拒绝</a>"}]
        ], 
    });
}

// 发起申请
$.fn.createWorkflowApplication = function(options){
    // 属性
    var options = $.extend({
        // 表单项类型
        "itemType": {
            "workflowItemTypeFromUser": "workflow-from-user",           // 发起人名称
            "workflowItemTypeCreatetime": "workflow-createtime",        // 发起时间
            "workflowItemTypeText": "workflow-text",                    // 文本框
            "workflowItemTypeTime": "workflow-time",                    // 时间选择
            "workflowItemTypeSelect": "workflow-select",                // 下拉选择
            "workflowItemTypeFile": "workflow-file",                    // 文件上传
            "workflowItemTypeContent": "workflow-content",              // 富文本编辑器
        },
        // timeformat
        "timeFormat": {
            "YYYY-MM-DD HH:mm:ss": "2019-05-31 17:00:00",
            "YYYY-MM-DD HH:mm": "2019-05-31 17:00",
            "YYYY-MM-DD": "2019-05-31",
            "HH:mm:ss": "17:00:00",
            "HH:mm": "17:00",
        },
        // 接收元素容器
        "droppableDom": null,
        // 初始化表单对象
        "formData": null,
        // 初始化默认数据对象
        "defaultData": null,
        // 回调函数
        callback: function(){}
    }, options);

    // 接收拖动元素
    var droppableDom = options.droppableDom;

    // 方法
    var createWorkflowApplicationFunction = {
        // 初始化表单设计器
        "design_init": function() {
            // 如果有初始化对象
            if(options.formData) {
                for(var itemId in options.formData) {
                    var formItem = options.formData[itemId];
                    // 初始化对象
                    formItem.id = itemId;
                    formItem.itemPlaceholder = droppableDom.find(".workflow-design-form-bottom");
                    createWorkflowApplicationFunction.create_design_item(formItem);
                }
            }
            // 提交表单
            $("#save-workflow-content").click(function(){
                var itemData = {};
                $(".workflow-design-item").each(function(){
                    var id = $(this).attr("id");
                    // 标签和格式
                    itemData[id] = {
                        "type": $(this).data('type'),
                        "label": $(this).data("label"),
                        "value": $(this).find("input").val() ? $(this).find("input").val().trim() : ''
                    }
                    // 时间格式
                    if(typeof $(this).data("format") != 'undefined') itemData[id].timeFormat = $(this).data("format");
                    // 下拉选项
                    if(typeof $(this).data("options") != 'undefined') itemData[id].selectOptions = $(this).data("options");
                    // 获取下拉选项
                    if($(this).data('type') == 'workflow-select'){
                        itemData[id].value = $(this).find("select").val().trim();
                    }
                    // 获取富文本文档内容
                    if($(this).data('type') == 'workflow-content'){
                        itemData[id].value = $(this).find("textarea").val() ? $(this).find("textarea").val().trim() : ''
                    }
                    // 获取上传文件内容
                    if($(this).data('type') == 'workflow-file' && $(".attachment-file").eq(0).data('name') != undefined){
                        var file = [];
                        $(".attachment-file").each(function() {
                            file.push({
                                "name": $(this).data('name'),
                                "type": $(this).data('type'),
                                "link": $(this).data('link')
                            });
                        });
                        itemData[id].value = file
                    }
                })
                // 执行回调
                options.callback(itemData);
            });
        },
        
        // 创建表单元素
        "create_design_item": function(dataJson){
            // 表单项占位符
            var itemPlaceholder = dataJson.itemPlaceholder;
            // 表单项类型
            var itemType = dataJson.type;
            // 表单项ID
            var itemId = typeof dataJson.id != 'undefined' ? dataJson.id : "id_" + parseInt(Math.random() * 10000000);
            // 表单项子元素ID
            var itemChildId = "id_" + parseInt(Math.random() * 10000);
            // 表单项标签
            var itemLabel = typeof dataJson.label != 'undefined' ? dataJson.label : '';
            // 表单项时间格式
            var itemTimeFormat = typeof dataJson.timeFormat != 'undefined' ? dataJson.timeFormat : '';
            // 表单项下拉菜单选项
            var itemSelectOptions = typeof dataJson.selectOptions != 'undefined' ? dataJson.selectOptions : '';

            // 生成不同的表单内容
            switch(itemType) {
                // 发起人
                case options.itemType.workflowItemTypeFromUser:
                    var label = itemLabel ? itemLabel : '发起人姓名';
                    var username = options.defaultData.username;
                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ label +'" data-type="'+ itemType +'">\
                            <label class="col-sm-3 control-label no-padding-right">'+ label +'：</label>\
                            <div class="col-sm-9">\
                                <input class="col-sm-8" type="text" value="' + username + '" readonly>\
                            </div>\
                        </div>');
                    break;
                // 发起时间
                case options.itemType.workflowItemTypeCreatetime:
                    var label = itemLabel ? itemLabel : '发起时间';
                    // 时间格式
                    var defaultFormat = itemTimeFormat ? itemTimeFormat : "YYYY-MM-DD HH:mm:ss";
                    var nowTime = options.defaultData.nowTime[defaultFormat];
                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ label +'" data-type="'+ itemType +'">\
                            <label class="col-sm-3 control-label no-padding-right">'+ label +'：</label>\
                            <div class="col-sm-9">\
                                <input class="col-sm-8 input" type="text" value="' + nowTime + '" readonly>\
                            </div>\
                        </div>');
                    break;
                // 文本框
                case options.itemType.workflowItemTypeText:
                    var label = itemLabel ? itemLabel : '工作流标题';

                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ label +'" data-type="'+ itemType +'">\
                            <label class="col-sm-3 control-label no-padding-right">'+ label +'：</label>\
                            <div class="col-sm-9">\
                                <input class="col-sm-8" type="text">\
                            </div>\
                        </div>');
                    break;
                // 日期时间选择
                case options.itemType.workflowItemTypeTime:
                    var label = itemLabel ? itemLabel : '请假开始时间';
                    // 时间格式
                    var defaultFormat = itemTimeFormat ? itemTimeFormat : "YYYY-MM-DD HH:mm:ss";
                    // var formatValue = options.timeFormat[defaultFormat];
                    var formatValue = options.defaultData.nowTime[defaultFormat];
                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ label +'" data-type="'+ itemType +'" data-format="'+ defaultFormat +'">\
                            <label class="col-sm-3 control-label no-padding-right">'+ label +'：</label>\
                            <div class="col-sm-9">\
                                <input class="col-sm-8 time-input" type="text" value="' + formatValue + '" data-timeformat="' + defaultFormat + '">\
                            </div>\
                        </div>');
                    break;
                // 下拉选择
                case options.itemType.workflowItemTypeSelect:
                    var label = itemLabel ? itemLabel : '类型选择';
                    // 下拉选项
                    var optionHtml = '<option>请选择对应的类型</option>';
                    if(itemSelectOptions != '') {
                        var optionsArray = itemSelectOptions.split(", ");
                        optionHtml = "";
                        for(var i in optionsArray) optionHtml += '<option value="'+ optionsArray[i] +'">'+ optionsArray[i] +'</option>';
                    }


                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ label +'" data-type="'+ itemType +'" data-options="'+ itemSelectOptions +'">\
                        <label class="col-sm-3 control-label no-padding-right">'+ label +'：</label>\
                        <div class="col-sm-9">\
                            <select class="col-sm-8 pd0">'+ optionHtml +'</select>\
                        </div>\
                    </div>');
                    break;
                // 文件上传
                case options.itemType.workflowItemTypeFile:
                    var label = itemLabel ? itemLabel : '文件上传';
                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ label +'" data-type="'+ itemType +'">\
                        <label class="col-sm-3 control-label no-padding-right">'+ label +'：</label>\
                        <div class="col-sm-6" style="padding-top: 9px;">\
                            <div class="no-border">\
                                <a href="javascript:;" class="" id="upload-file"><i class="fa fa-file"></i> 上传附件</a>\
                            </div>\
                            <ul class="attachment-list pull-left list-unstyled" id="file-div">\
                            </ul>\
                        </div>\
                    </div>');
                    break;
                // 富文本编辑器
                case options.itemType.workflowItemTypeContent:
                    var label = itemLabel ? itemLabel : '内容说明';
                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ label +'" data-type="'+ itemType +'" data-options="">\
                        <label class="col-sm-3 control-label no-padding-right">'+ label +'：</label>\
                        <div class="col-sm-9">\
                            <div class="col-sm-8 no-border" style="padding-top: 10px;">\
                                <textarea id="' + itemChildId + '" name="class_content" style="width:100%;height:120px"></textarea>\
                            </div>\
                        </div>\
                    </div>');
                    // 初始化百度编辑器
                    var ue = UE.getEditor(itemChildId);
                    break;
            }
        }
    }

    // 初始化方法
    createWorkflowApplicationFunction.design_init();     
}

// 查看申请
$.fn.checkWorkflowApplication = function(options){
    // 属性
    var options = $.extend({
        // 表单项类型
        "itemType": {
            "workflowItemTypeFromUser": "workflow-from-user",           // 发起人名称
            "workflowItemTypeCreatetime": "workflow-createtime",        // 发起时间
            "workflowItemTypeText": "workflow-text",                    // 文本框
            "workflowItemTypeTime": "workflow-time",                    // 时间选择
            "workflowItemTypeSelect": "workflow-select",                // 下拉选择
            "workflowItemTypeFile": "workflow-file",                    // 文件上传
            "workflowItemTypeContent": "workflow-content",              // 富文本编辑器
        },
        // timeformat
        "timeFormat": {
            "YYYY-MM-DD HH:mm:ss": "2019-05-31 17:00:00",
            "YYYY-MM-DD HH:mm": "2019-05-31 17:00",
            "YYYY-MM-DD": "2019-05-31",
            "HH:mm:ss": "17:00:00",
            "HH:mm": "17:00",
        },
        // 接收元素容器
        "droppableDom": null,
        // 初始化表单对象
        "formData": null,
        // 初始化默认数据对象
        "defaultData": null,
    }, options);

    // 接收拖动元素
    var droppableDom = options.droppableDom;

    // 方法
    var checkWorkflowApplicationFunction = {
        // 初始化表单设计器
        "design_init": function() {
            // 如果有初始化对象
            if(options.formData) {
                for(var itemId in options.formData) {
                    var formItem = options.formData[itemId];
                    // 初始化对象
                    formItem.id = itemId;
                    formItem.itemPlaceholder = droppableDom.find(".workflow-design-form-bottom");
                    checkWorkflowApplicationFunction.create_design_item(formItem);
                }
            }
        },
        
        // 创建表单元素
        "create_design_item": function(dataJson){
            // 表单项占位符
            var itemPlaceholder = dataJson.itemPlaceholder;
            // 表单项类型
            var itemType = dataJson.type;
            // 表单项ID
            var itemId = typeof dataJson.id != 'undefined' ? dataJson.id : "id_" + parseInt(Math.random() * 10000000);
            // 表单项子元素ID
            var itemChildId = "id_" + parseInt(Math.random() * 10000);
            // 表单项标签
            var itemLabel = typeof dataJson.label != 'undefined' ? dataJson.label : '';
            // 表单项下拉菜单选项
            var itemSelectOptions = typeof dataJson.selectOptions != 'undefined' ? dataJson.selectOptions : '';
            // 表单值
            var value = dataJson.value;
            // 生成不同的表单内容
            switch(itemType) {
                // 发起人
                case options.itemType.workflowItemTypeFromUser:
                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ itemLabel +'" data-type="'+ itemType +'">\
                            <label class="col-sm-3 control-label no-padding-right">'+ itemLabel +'：</label>\
                            <div class="col-sm-9">\
                                <input class="col-sm-8" type="text" value="' + value + '" readonly>\
                            </div>\
                        </div>');
                    break;
                // 发起时间
                case options.itemType.workflowItemTypeCreatetime:
                    // 时间格式
                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ itemLabel +'" data-type="'+ itemType +'">\
                            <label class="col-sm-3 control-label no-padding-right">'+ itemLabel +'：</label>\
                            <div class="col-sm-9">\
                                <input class="col-sm-8 input" type="text" value="' + value + '" readonly>\
                            </div>\
                        </div>');
                    break;
                // 文本框
                case options.itemType.workflowItemTypeText:
                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ itemLabel +'" data-type="'+ itemType +'">\
                            <label class="col-sm-3 control-label no-padding-right">'+ itemLabel +'：</label>\
                            <div class="col-sm-9">\
                                <input class="col-sm-8" type="text" value="' + value + '" readonly>\
                            </div>\
                        </div>');
                    break;
                // 日期时间选择
                case options.itemType.workflowItemTypeTime:
                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ itemLabel +'" data-type="'+ itemType +'">\
                            <label class="col-sm-3 control-label no-padding-right">'+ itemLabel +'：</label>\
                            <div class="col-sm-9">\
                                <input class="col-sm-8 input" type="text" value="' + value + '" readonly>\
                            </div>\
                        </div>');
                    break;
                // 下拉选择
                case options.itemType.workflowItemTypeSelect:
                    // 下拉选项
                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ itemLabel +'" data-type="'+ itemType +'" data-options="'+ itemSelectOptions +'">\
                        <label class="col-sm-3 control-label no-padding-right">'+ itemLabel +'：</label>\
                        <div class="col-sm-9">\
                        <input class="col-sm-8 input" type="text" value="' + value + '" readonly>\
                        </div>\
                    </div>');
                    break;
                // 文件上传
                case options.itemType.workflowItemTypeFile:
                    {
                        if(value){
                            var html = '';
                            for(var index in value){
                                html += '<li class="attachment-file" data-name="'+ value[index].name +'" data-type="'+ value[index].type +'" data-link="'+ value[index].link +'">\
                                    <a href="'+ value[index].link +'" target="_blank" class="attached-file">\
                                        <i class="ace-icon fa fa-film bigger-110"></i>\
                                        <span class="attached-name">'+ value[index].name +'</span>\
                                    </a>\
                                </li>';
                            }
                            itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ itemLabel +'" data-type="'+ itemType +'">\
                            <label class="col-sm-3 control-label no-padding-right">'+ itemLabel +'：</label>\
                                <ul class="attachment-list pull-left list-unstyled" id="file-div">' + html + '</ul>\
                            </div>');
                        } else{
                            itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ itemLabel +'" data-type="'+ itemType +'">\
                                <label class="col-sm-3 control-label no-padding-right">'+ itemLabel +'：</label>\
                                <div class="col-sm-3" style="padding: 9px 0 0 15px;">无</div>\
                            </div>'); 
                        }
                    }
                    
                    break;
                // 富文本编辑器
                case options.itemType.workflowItemTypeContent:
                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ itemLabel +'" data-type="'+ itemType +'" data-options="">\
                        <label class="col-sm-3 control-label no-padding-right">'+ itemLabel +'：</label>\
                        <div class="col-sm-9">\
                            <div class="col-sm-8 no-border" style="padding-top: 10px;">' + value + '</div>\
                        </div>\
                    </div>');
                    break;
            }
        }
    }

    // 初始化方法
    checkWorkflowApplicationFunction.design_init();     
}

// 修改申请
$.fn.editWorkflowApplication = function(options){
    // 属性
    var options = $.extend({
        // 表单项类型
        "itemType": {
            "workflowItemTypeFromUser": "workflow-from-user",           // 发起人名称
            "workflowItemTypeCreatetime": "workflow-createtime",        // 发起时间
            "workflowItemTypeText": "workflow-text",                    // 文本框
            "workflowItemTypeTime": "workflow-time",                    // 时间选择
            "workflowItemTypeSelect": "workflow-select",                // 下拉选择
            "workflowItemTypeFile": "workflow-file",                    // 文件上传
            "workflowItemTypeContent": "workflow-content",              // 富文本编辑器
        },
        // timeformat
        "timeFormat": {
            "YYYY-MM-DD HH:mm:ss": "2019-05-31 17:00:00",
            "YYYY-MM-DD HH:mm": "2019-05-31 17:00",
            "YYYY-MM-DD": "2019-05-31",
            "HH:mm:ss": "17:00:00",
            "HH:mm": "17:00",
        },
        // 接收元素容器
        "droppableDom": null,
        // 初始化表单对象
        "formData": null,
        // 初始化默认数据对象
        "defaultData": null,
    }, options);

    // 接收拖动元素
    var droppableDom = options.droppableDom;

    // 方法
    var editWorkflowApplicationFunction = {
        // 初始化表单设计器
        "design_init": function() {
            // 如果有初始化对象
            if(options.formData) {
                for(var itemId in options.formData) {
                    var formItem = options.formData[itemId];
                    // 初始化对象
                    formItem.id = itemId;
                    formItem.itemPlaceholder = droppableDom.find(".workflow-design-form-bottom");
                    editWorkflowApplicationFunction.create_design_item(formItem);
                }
            }
            // 提交表单
            $("#edit-application").click(function(){
                var itemData = {};
                $(".workflow-design-item").each(function(){
                    var id = $(this).attr("id");
                    // 标签和格式
                    itemData[id] = {
                        "type": $(this).data('type'),
                        "label": $(this).data("label"),
                        "value": $(this).find("input").val() ? $(this).find("input").val().trim() : ''
                    }
                    // 时间格式
                    if(typeof $(this).data("format") != 'undefined') itemData[id].timeFormat = $(this).data("format");
                    // 下拉选项
                    if(typeof $(this).data("options") != 'undefined') itemData[id].selectOptions = $(this).data("options");
                    // 获取下拉选项
                    if($(this).data('type') == 'workflow-select'){
                        itemData[id].value = $(this).find("select").val().trim();
                    }
                    // 获取富文本文档内容
                    if($(this).data('type') == 'workflow-content'){
                        itemData[id].value = $(this).find("textarea").val() ? $(this).find("textarea").val().trim() : ''
                    }
                    // 获取上传文件内容
                    if($(this).data('type') == 'workflow-file' && $(".attachment-file").eq(0).data('name') != undefined){
                        var file = [];
                        $(".attachment-file").each(function() {
                            file.push({
                                "name": $(this).data('name'),
                                "type": $(this).data('type'),
                                "link": $(this).data('link')
                            });
                        });
                        itemData[id].value = file
                    }
                })
                // 执行回调
                options.callback(itemData);
            });
        },
        
        // 创建表单元素
        "create_design_item": function(dataJson){
            // 表单项占位符
            var itemPlaceholder = dataJson.itemPlaceholder;
            // 表单项类型
            var itemType = dataJson.type;
            // 表单项ID
            var itemId = typeof dataJson.id != 'undefined' ? dataJson.id : "id_" + parseInt(Math.random() * 10000000);
            // 表单项子元素ID
            var itemChildId = "id_" + parseInt(Math.random() * 10000);
            // 表单项标签
            var itemLabel = typeof dataJson.label != 'undefined' ? dataJson.label : '';
            // 表单项时间格式
            var itemTimeFormat = typeof dataJson.timeFormat != 'undefined' ? dataJson.timeFormat : '';
            // 表单项下拉菜单选项
            var itemSelectOptions = typeof dataJson.selectOptions != 'undefined' ? dataJson.selectOptions : '';
            // 表单值
            var value = dataJson.value;
            // 生成不同的表单内容
            switch(itemType) {
                // 发起人
                case options.itemType.workflowItemTypeFromUser:
                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ itemLabel +'" data-type="'+ itemType +'">\
                            <label class="col-sm-3 control-label no-padding-right">'+ itemLabel +'：</label>\
                            <div class="col-sm-9">\
                                <input class="col-sm-8" type="text" value="' + value + '" readonly>\
                            </div>\
                        </div>');
                break;
                // 发起时间
                case options.itemType.workflowItemTypeCreatetime:
                    // 时间格式
                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ itemLabel +'" data-type="'+ itemType +'">\
                            <label class="col-sm-3 control-label no-padding-right">'+ itemLabel +'：</label>\
                            <div class="col-sm-9">\
                                <input class="col-sm-8 input" type="text" value="' + value + '" readonly>\
                            </div>\
                        </div>');
                break;
                // 文本框
                case options.itemType.workflowItemTypeText:
                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ itemLabel +'" data-type="'+ itemType +'">\
                            <label class="col-sm-3 control-label no-padding-right">'+ itemLabel +'：</label>\
                            <div class="col-sm-9">\
                                <input class="col-sm-8" type="text" value="' + value + '">\
                            </div>\
                        </div>');
                break;
                // 日期时间选择
                case options.itemType.workflowItemTypeTime:
                    var label = itemLabel ? itemLabel : '请假开始时间';
                    // 时间格式
                    var defaultFormat = itemTimeFormat ? itemTimeFormat : "YYYY-MM-DD HH:mm:ss";
                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ label +'" data-type="'+ itemType +'" data-format="'+ defaultFormat +'">\
                            <label class="col-sm-3 control-label no-padding-right">'+ label +'：</label>\
                            <div class="col-sm-9">\
                                <input class="col-sm-8 time-input" type="text" value="' + value + '" data-timeformat="' + defaultFormat + '">\
                            </div>\
                        </div>');
                break;
                // 下拉选择
                case options.itemType.workflowItemTypeSelect:
                    var label = itemLabel ? itemLabel : '类型选择';
                    // 下拉选项
                    var optionHtml = '<option>请选择对应的类型</option>';
                    if(itemSelectOptions != '') {
                        var optionsArray = itemSelectOptions.split(", ");
                        optionHtml = "";
                        for(var i in optionsArray) {
                            if(value == optionsArray[i]){
                                optionHtml += '<option value="'+ optionsArray[i] +'" selected>'+ optionsArray[i] +'</option>';
                            } else {
                                optionHtml += '<option value="'+ optionsArray[i] +'">'+ optionsArray[i] +'</option>';
                            }
                        }
                    }

                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ label +'" data-type="'+ itemType +'" data-options="'+ itemSelectOptions +'">\
                        <label class="col-sm-3 control-label no-padding-right">'+ label +'：</label>\
                        <div class="col-sm-9">\
                            <select class="col-sm-8 pd0">'+ optionHtml +'</select>\
                        </div>\
                    </div>');
                break;
                // 文件上传
                case options.itemType.workflowItemTypeFile:
                    var label = itemLabel ? itemLabel : '文件上传';
                    var html = '';
                    if(value){
                        for(var index in value){
                            html += '<li class="attachment-file" data-name="'+ value[index].name +'" data-type="'+ value[index].type +'" data-link="'+ value[index].link +'">\
                                <a href="'+ value[index].link +'" target="_blank" class="attached-file">\
                                    <i class="ace-icon fa fa-film bigger-110"></i>\
                                    <span class="attached-name">'+ value[index].name +'</span>\
                                </a>\
                                <span class="action-buttons" style="position:relative; top:3px;">\
                                    <a href="'+ value[index].link +'" target="_blank">\
                                        <i class="ace-icon fa fa-download bigger-125 blue"></i>\
                                    </a>\
                                    <a href="javascript:;" class="remove-file">\
                                        <i class="ace-icon fa fa-trash-o bigger-125 red"></i>\
                                    </a>\
                                </span>\
                            </li>';
                        }
                    }
                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ label +'" data-type="'+ itemType +'">\
                    <label class="col-sm-3 control-label no-padding-right">'+ label +'：</label>\
                        <div class="col-sm-6" style="padding-top: 9px;">\
                            <div class="no-border">\
                                <a href="javascript:;" class="" id="upload-file"><i class="fa fa-file"></i> 上传附件</ a>\
                            </div>\
                            <ul class="attachment-list pull-left list-unstyled" id="file-div">' + html + '</ul>\
                        </div>\
                    </div>');
                break;
                // 富文本编辑器
                case options.itemType.workflowItemTypeContent:
                    itemPlaceholder.before('<div id="'+ itemId +'" class="form-group workflow-design-item" data-label="'+ itemLabel +'" data-type="'+ itemType +'" data-options="">\
                        <label class="col-sm-3 control-label no-padding-right">'+ itemLabel +'：</label>\
                        <div class="col-sm-9">\
                            <div class="col-sm-8 no-border" style="padding-top: 10px;">\
                                <textarea id="' + itemChildId + '" name="class_content" style="width:100%;height:120px">' + value + '</textarea>\
                            </div>\
                        </div>\
                    </div>');
                // 初始化百度编辑器
                var ue = UE.getEditor(itemChildId);
                break;
            }
        }
    }

    // 初始化方法
    editWorkflowApplicationFunction.design_init();     
}